package com.imjohn.controller;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class WxGetUrlLink {
    private static final String AppID = "wx8b6f7ec37487ab03"; //开发者ID
    private static final String AppSecret = "ca30dbdee5aa5a2ea60bf43415f022a7"; //开发者密码
//    private static final String AppID = "wxcbff648c8282326e"; //开发者ID
//    private static final String AppSecret = "15b1b469081234877310812aef36041f"; //开发者密码
    private static String access_token = ""; //调用接口的凭证 2个小时后就会过期需要重新获取 一天最多获取2千次
    private static String mp_link = ""; // 小程序url


    @RequestMapping("/getMpUrlLink")
    public Map Share (@RequestBody HashMap wxmap){
        String token = (String) wxmap.get("token");//获取过渡页token
        String getData = (String) wxmap.get("data");//获取过渡页token
        HashMap wxShare = getMpLink(token, getData);//随机串、签名的时间戳、签名字符串
        return wxShare;

    }


    //获取微信urlLink
    public HashMap getMpLink(String token, String data){//url 即为访问网站的url
        //打开浏览器，创建HTTPClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //第一步 判断access_token 与 jsapi_ticket是否过期 如果过期了就重新获取

        //通过appid和appsecret，就可以向微信平台来换取access_token
        String token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WxGetUrlLink.AppID+"&secret="+WxGetUrlLink.AppSecret;
        HttpGet httpGet = new HttpGet(token_access_url);
        CloseableHttpResponse response = null;//按回车，发起请求
        try {
            response = httpClient.execute(httpGet);
            //解析响应 判断状态码是否是200
            if (response.getStatusLine().getStatusCode()==200){
                HttpEntity httpEntity = response.getEntity();//获取响应消息实体
                String body = EntityUtils.toString(httpEntity);//获取返回的消息文本
                JSONObject jsonObject = JSONObject.fromObject(body);//将消息文本解析成json
                String access_token = (String) jsonObject.get("access_token");
                WxGetUrlLink.access_token = access_token;
            }
            //第二步 通过access_token，生成小程序urlLink
            String mp_link = "https://api.weixin.qq.com/wxa/generate_urllink?access_token="+ WxGetUrlLink.access_token;
            HttpPost httpPost = new HttpPost(mp_link);
            httpPost.setHeader("Content-type", "appication/json; charset=UTF-8");
            Map setparam = new HashMap<>();
//            setparam.put("access_token", WxGetUrlLink.access_token);
            setparam.put("path", "pages/index/index");
            setparam.put("query", "data=" + data +"&token="+ token);
            setparam.put("env_version", "trial");
            String amit = JSON.toJSONString(setparam);
            StringEntity aa = new StringEntity(amit);
            httpPost.setEntity(aa);
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode()==200){//解析响应 判断状态码是否是200
                HttpEntity httpEntity = response.getEntity();//获取响应消息实体
                String body = EntityUtils.toString(httpEntity);//获取返回的消息文本
                JSONObject jsonObject = JSONObject.fromObject(body);//将消息文本解析成json
                String errmsg = (String) jsonObject.get("errmsg");
                if(errmsg.trim().equals("ok")){
                    String get_link = (String) jsonObject.get("url_link");
                    WxGetUrlLink.mp_link = get_link;

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            try {response.close();} catch (IOException e) {e.printStackTrace();}
            try {httpClient.close();} catch (IOException e) {e.printStackTrace();}
        }
        Map map = new HashMap<>();
        map.put("token", WxGetUrlLink.mp_link);
        return (HashMap) map;
    }

}
